package cn.kmsoft.jssc.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : cqwensten
 * @description : todo
 * @email : cqwensten@163.com
 * @date : 2023/1/28
 */
@Configuration
public class RestCfg {
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        RestTemplate restTemplate = new RestTemplate(factory);
        restTemplate.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());
        return restTemplate;
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        // PoolingHttpClientConnectionManager connectionManager = new
        // PoolingHttpClientConnectionManager();
        // connectionManager.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).build());
        // connectionManager.setDefaultMaxPerRoute(20);
        // connectionManager.setMaxTotal(200); // 总的最大连接数
        // HttpClient httpClient =
        // HttpClientBuilder.create().setConnectionManager(connectionManager).build();
        // HttpComponentsClientHttpRequestFactory factory = new
        // HttpComponentsClientHttpRequestFactory(httpClient);
        // factory.setReadTimeout(30 * 1000);
        // factory.setConnectTimeout(30 * 1000);
        // factory.setConnectionRequestTimeout(30 * 1000);

        SslClientHttpRequestFactory factory = new SslClientHttpRequestFactory();
        factory.setReadTimeout(900000);
        factory.setConnectTimeout(15000);
        return factory;
    }

}

class WxMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {
    public WxMappingJackson2HttpMessageConverter() {
        List<MediaType> mediaTypes = new ArrayList<>();
        mediaTypes.add(MediaType.TEXT_PLAIN);
        mediaTypes.add(MediaType.TEXT_HTML);
        mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        setSupportedMediaTypes(mediaTypes);
    }
}
